<template>
  <div class=".list-pagination dish-management-container">
    <el-card style="margin-top:10px">
      <div slot="header">
        <div class="dish-management-container-header">
          <el-input v-model="dishName" class="input" placeholder="请输入菜品名称" @keydown.enter.native="searchDish">
            <el-button slot="append" icon="el-icon-search" style="padding:0" @click="searchDish" />
          </el-input>
          <div class="dish-management-container-header-batch-operation">
            <el-link :underline="false" type="danger" @click="batchDelete">批量删除</el-link>
            <el-divider direction="vertical" />
            <el-link :underline="false" type="success" @click="batchStartOrEndSale(1)">批量启售</el-link>
            <el-divider direction="vertical" />
            <el-link :underline="false" type="warning" @click="batchStartOrEndSale(0)">批量停售</el-link>
            <el-button type="primary" size="mini" @click="showAddDish">添加菜品</el-button>
          </div>
        </div>
      </div>
      <div>
        <el-table
          ref="dishInformation"
          :data="dishInformation"
          border
          style="width: 100%"
          :row-key="getRowKey"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            prop="name"
            label="菜品名称"
            min-width="150px"
          />
          <el-table-column
            prop="image"
            label="图片"
            min-width="120px"
            align="center"
          >
            <template slot-scope="scope">
              <img :src="downloadImg(scope.row.image)" alt="菜品图片" :onerror="defaultImg">
            </template>
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="商品分类"
            min-width="100px"
            align="center"
          />
          <el-table-column
            prop="price"
            label="售价"
            min-width="100px"
            align="center"
            :formatter="formatterPrice"
          />
          <el-table-column
            prop="status"
            label="售卖状态"
            align="center"
            min-width="100px"
            :formatter="formatterStatus"
          />
          <el-table-column
            prop="updateTime"
            label="最后操作时间"
            min-width="180px"
            align="center"
          />
          <el-table-column label="操作" align="center" width="150px">
            <template slot-scope="scope">
              <el-link
                size="mini"
                :underline="false"
                @click="handleChange(scope.$index, scope.row)"
              >修改</el-link>
              <el-link
                :underline="false"
                size="mini"
                type="warning"
                @click="handleChangeStatus(scope.$index, scope.row)"
              >{{ formatterStatus(scope.row) =='起售'?'停售':'起售' }}</el-link>
              <el-link
                :underline="false"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.id)"
              >删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="paginationInfo.total > 0"
          :total="paginationInfo.total"
          :page.sync="paginationInfo.page"
          :limit="paginationInfo.pageSize"
          @pagination="getTableList"
        />
      </div>
    </el-card>
    <add-dish v-if="showAddDishDialog" :show.sync="showAddDishDialog" :is-edit="isEdit" :dish-id="dishId" />
  </div>
</template>

<script>
import AddDish from '@/views/dishManagement/components/AddDish'
import { getDishList, deleteDish, dishStatusByStatus, downloadImg } from '@/api/dish'
import { EventBus } from '@/utils/eventBus'
import pagination from '@/components/pagination'
export default {
  components: { AddDish, pagination },
  data() {
    return {
      dishName: '',
      dishInformation: [],
      dishId: '',
      isEdit: false,
      showAddDishDialog: false,
      multipleSelection: [],
      paginationInfo: {
        pageSize: 10,
        page: 1,
        total: 0
      },
      defaultImg: 'this.src="' + require('../../assets/defaultImg/noImg.png') + '"'
    }
  },
  created() {
    this.getTableList()
  },
  mounted() {
    EventBus.$on('retchDishData', () => {
      this.paginationInfo.current = 1
      this.getTableList()
    })
  },
  methods: {
    async getTableList(obj) {
      if (obj) {
        const { page, limit } = obj
        this.paginationInfo.page = page
        this.paginationInfo.pageSize = limit
      }
      const { page, pageSize } = this.paginationInfo
      const { data } = await getDishList({ page, pageSize, name: this.dishName })
      console.log(data)
      if (data) {
        this.dishInformation = data.records || []
        this.paginationInfo.total = data.total
      }
    },
    searchDish() {
      this.paginationInfo.page = 1
      this.getTableList()
    },
    showAddDish() {
      this.showAddDishDialog = true
      this.isEdit = false
    },
    formatterStatus(row) {
      return row.status === 1 ? '起售' : '停售'
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    async handleDelete(id) {
      this.$confirm('是否删除所选商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteDish(id)
        if (res?.code) {
          this.$message.success('删除成功')
          this.paginationInfo.page = 1
          this.getTableList()
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleChangeStatus(index, row) {
      this.$confirm('是否切换该菜品状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        row.status = row.status === 1 ? 0 : 1
        const result = await dishStatusByStatus(row)
        if (result?.code) {
          this.$message({
            type: 'success',
            message: '更改成功!'
          })
          this.getTableList()
        }
      }).catch((err) => {
        this.$message({
          type: 'error',
          message: err.msg || '已取消操作'
        })
      })
    },
    handleChange(index, row) {
      this.dishId = row.id
      this.isEdit = true
      this.showAddDishDialog = true
    },
    batchDelete(rows) {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择需要删除的商品')
        return
      }
      const ids = this.multipleSelection.map((item) => item.id).join(',')
      this.handleDelete(ids)
    },
    batchStartOrEndSale(status) {
      if (this.multipleSelection.length === 0) {
        this.$message.error(`请选择需要${status ? '起售' : '停售'}的菜品`)
        return
      }
      this.$confirm(`${status ? '是否起售所有选中的菜品?' : '是否停售所有选中的菜品'}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const id = this.multipleSelection.map((item) => item.id).join(',')
        console.log(id)
        const result = await dishStatusByStatus({ status, id })
        console.log(result)
        if (result?.code) {
          this.$message({
            type: 'success',
            message: '更改成功!'
          })
          this.paginationInfo.page = 1
          this.getTableList()
        }
      }).catch((err) => {
        this.$message({
          type: 'error',
          message: err.msg || '已取消操作'
        })
      })
    },
    getRowKey(row) {
      return row.id
    },
    formatterPrice(row) {
      return '￥' + row.price / 100
    },
    downloadImg(name) {
      return downloadImg(name)
    }
  }
}
</script>

<style lang="scss">
$bg:grey;
.dish-management{
  &-container {
    background-color: $bg;
    margin: 10px;
    .el-link{
      margin: 5px;
    }
    &-header{
      display: flex;

      &-batch-operation{
        margin-left: auto;
        .el-button{
          margin-left: auto;
        }
      }

      .input{
        width: 250px;
        .el-button{
          margin: 0 !important;
        }
      }
    }
    img{
    height: 30px;
    width: 30px;
  }
  }
}
</style>

